import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/dms_documenttype_odoo_api.dart';
import 'package:flutter_admin/api/odoo/dms_file_odoo_api.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/udt_tb_docmentstock_odoo_api.dart';
import 'package:flutter_admin/constants/constant_dict.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/dms_documenttype.dart';
import 'package:flutter_admin/models/odoo/dms_file.dart';
import 'package:flutter_admin/models/odoo/udt_tb_docmentstock.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/select_docmenttype_dialog.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/udt_tb_docmentstock_dialog.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/udt_tb_docmentstock_edit.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/lend_or_return.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/utils/utils.dart';



class SelectDocmenttypeList extends StatefulWidget {

  SelectDocmenttypeList({Key? key}) : super(key: key);

  @override
  _SelectDocmenttypeListState createState() => _SelectDocmenttypeListState();
}

class _SelectDocmenttypeListState extends State<SelectDocmenttypeList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
  PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  DmsDocumenttype dmsDocumenttype = DmsDocumenttype();
  List<DmsDocumenttype> selectedList = [];
  bool flag = true;
  // List<SelectOptionVO> departmentList = [];
  @override
  void initState() {
    var deparment =
    StoreUtil.read(Constant.KEY_CURRENT_USER_INFO)[0]["department_id"];
    dmsDocumenttype.departmentId = deparment[0].toString();
    dmsDocumenttype.departmentName = deparment[1].toString();
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
      // _loadSelectVO();
    });
  }

  // _loadSelectVO() async {
  //   departmentList = await DynamicDataApi.getModelSelect(
  //     model: "hr.department",
  //     name: "complete_name",
  //   );
  //   setState(() {});
  // }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          // CrySelect(
          //   width: 280,
          //   label: '部门',
          //   dataList: departmentList,
          //   value: dmsDocumenttype.departmentId,
          //   onSaved: (v) {
          //     dmsDocumenttype.departmentId = v;
          //   },
          // ),
          CryInput(
            width: 280,
            label: '部门',
            enable: false,
            value: dmsDocumenttype.departmentName,
            onSaved: (v) {
              dmsDocumenttype.departmentName = v;
            },
          ),
          CryInput(
            width: 280,
            label: '档案项目名称',
            value: dmsDocumenttype.documenttypename,
            onSaved: (v) {
              dmsDocumenttype.documenttypename = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
        _operationList(),
      ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        if (flag) {
          Navigator.pop(context, selected);
        }
        flag = false;
      },
      columns: [
        //isDisplayDesktop(context)?DataColumn(
        //  label: Text(S.of(context).operating),
        //):DataColumn(label: Container()),
        DataColumn(
          label: Text('档案项目代码'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('档案项目名称'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('所属部门'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('部门代码'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('保存期限(年)'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('归档责任人'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('范围'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('创建人'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('创建日期'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
      ],
      getCells: (m) {
        DmsDocumenttype dmsDocumenttype = DmsDocumenttype.fromMap(m);
        return [
          //isDisplayDesktop(context)?DataCell(
          //  CryButtonBar(
          //    children: [
          //      CryButton(
          //          iconData: Icons.edit,
          //          tip: S.of(context).modify,
          //          onPressed: () => _edit(dmsDocumenttype)),
          //    ],
          //  ),
          // ):DataCell(Container()),
          DataCell(Text(dmsDocumenttype.documenttypecode ?? '--')),
          DataCell(Text(dmsDocumenttype.documenttypename ?? '--')),
          DataCell(Text(dmsDocumenttype.departmentName ?? '--')),
          DataCell(Text(dmsDocumenttype.departmentcode ?? '--')),
          // DataCell(Text(dmsDocumenttype.shelflife ?? '--')),
          DataCell(Text((dmsDocumenttype.shelflife != null)
              ? dmsDocumenttype.shelflife.toString()
              : '--')),
          DataCell(Text(dmsDocumenttype.saveperson ?? '--')),
          DataCell(Text(dmsDocumenttype.range ?? '--')),
          DataCell(Text(dmsDocumenttype.createBy ?? '--')),
          DataCell(Text(Utils.timeUTC(dmsDocumenttype.createDate) ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            final ScaffoldState? scaffold = Scaffold
                .maybeOf(context);
            final ModalRoute<Object?>? parentRoute = ModalRoute.of(context);
            final bool canPop = parentRoute?.canPop ?? false;
            if (canPop) {
              return BackButton();
            } else {
              return SizedBox.shrink();
            }
          },
        ),
        title: Text('选择档案项目'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() {
    dmsDocumenttype = DmsDocumenttype();
    var deparment =
    StoreUtil.read(Constant.KEY_CURRENT_USER_INFO)[0]["department_id"];
    dmsDocumenttype.departmentId = deparment[0].toString();
    dmsDocumenttype.departmentName = deparment[1].toString();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await DmsDocumenttypeOdooApi.page(
        data: {"page": page, "domainList": dmsDocumenttype.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _sort(column, {ascending}) {
    page.orders[0].column = column;
    page.orders[0].asc = ascending ?? !page.orders[0].asc!;
    _query();
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: SelectDocumenttypeDialog(),
      ),
    ).then((v) {
      if (v != null) {
        dmsDocumenttype = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
        ?.getSelectedList(page)
        .map<DmsDocumenttype>((e) => DmsDocumenttype.fromMap(e))
        .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
      ],
    );
  }


}
